package com.hulk.dryad.web.oauth2.handler;


import com.hulk.dryad.common.util.WebUtils;
import com.hulk.dryad.manage.framework.tenant.KeyStrResolver;
import com.hulk.dryad.manage.security.handler.AuthenticationFailureEventHandler;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author hulk
 * @date 2019/10/8
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class DryadAuthenticationFailureEventEventHandler implements AuthenticationFailureEventHandler {

	private final KeyStrResolver tenantKeyStrResolver;
	/**
	 * 异步处理，登录失败方法
	 * <p>
	 * @param authenticationException 登录的authentication 对象
	 * @param authentication 登录的authenticationException 对象
	 * @param request 请求
	 * @param response 响应
	 */
	@Override
	@SneakyThrows
	public void handle(AuthenticationException authenticationException, Authentication authentication,
			HttpServletRequest request, HttpServletResponse response) {
		String username = authentication.getName();
		String header = request.getHeader(HttpHeaders.AUTHORIZATION);
		String serviceId = WebUtils.extractClientId(header).orElse("N/A");
		String tenantId = tenantKeyStrResolver.key();
		String localizedMessage = authenticationException.getLocalizedMessage();

		log.error("用户：[{}] header：[{}] 登录成功, 服务ID：[{}] 租户ID：[{}], 异常：{}", username,header,serviceId,tenantId,localizedMessage);
	}

}
